package store.lunangangster.engine.impl.cmd;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.NodeFlowObjectNotFoundException;
import store.lunangangster.engine.impl.auth.Authentication;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.IdentityLinkEntity;
import store.lunangangster.engine.impl.entity.TaskEntity;
import store.lunangangster.engine.impl.entity.mgr.IdentityLinkEntityManager;
import store.lunangangster.engine.impl.entity.mgr.TaskEntityManager;
import store.lunangangster.engine.impl.interceptor.CommandContext;

public class CompleteTaskCmd implements Command<Void> {

  private static final Logger log = LoggerFactory.getLogger(CompleteTaskCmd.class);

  protected String taskId;

  public CompleteTaskCmd(String taskId) {
    this.taskId = taskId;
  }


  @Override
  public Void execute(CommandContext commandContext) {
    TaskEntityManager taskEntityManager = commandContext.getProcessEngineConfiguration()
        .getTaskEntityManager();

    TaskEntity taskEntity = taskEntityManager.selectById(taskId);
    if (taskEntity == null) {
      throw new NodeFlowObjectNotFoundException("找不到id为: " + taskId + " 的Task");
    }
    executeCompleteTaskEntity(commandContext, taskEntity);
    return null;
  }

  protected void executeCompleteTaskEntity(CommandContext commandContext, TaskEntity taskEntity) {
    IdentityLinkEntityManager identityLinkEntityManager = commandContext.getProcessEngineConfiguration()
        .getIdentityLinkEntityManager();

    List<IdentityLinkEntity> identityLinkEntities = identityLinkEntityManager.selectIdentityLinkByTaskId(
        taskId);
    if (!checkAuthentication(identityLinkEntities)) {
      throw new NodeFlowException("当前用户没有权限执行任务: " + taskEntity.getName());
    }
    // finish task
    log.debug("【user: {}, group: {}】完成任务{}", Authentication.getUserId(), Authentication.getGroup(), taskEntity.getName());
    commandContext.getProcessEngineConfiguration().getTaskEntityManager().deleteTask(taskEntity.getId());

    ExecutionEntity execution = commandContext.getProcessEngineConfiguration()
        .getExecutionEntityManager().selectById(taskEntity.getExecutionId());
    // trigger Execution
    commandContext.getAgenda().addTriggerExecutionOperation(execution);
  }

  private boolean checkAuthentication(List<IdentityLinkEntity> identityLinkEntities) {
    String userId = Authentication.getUserId();
    String group = Authentication.getGroup();
    if (identityLinkEntities == null || identityLinkEntities.isEmpty()) {
      return true;
    }
    for (IdentityLinkEntity identityLink : identityLinkEntities) {
      if (identityLink.getUser() == null && identityLink.getGroup() == null) {
        return true;
      }
      if (identityLink.getUser() != null && identityLink.getUser().equals(userId)) {
        return true;
      }
      if (identityLink.getGroup() != null && identityLink.getGroup().equals(group)) {
        return true;
      }
    }
    return false;
  }
}
